package com.wlw.equipment.service.impl;

import com.wlw.equipment.mapper.EquipmentMapper;
import com.wlw.equipment.pojo.Equipment;
import com.wlw.equipment.pojo.EquipmentDoc;
import com.wlw.equipment.pojo.PageResult;
import com.wlw.equipment.pojo.RequestParams;
import com.wlw.equipment.service.IEquipmentService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EquipmentService extends ServiceImpl<EquipmentMapper, Equipment> implements IEquipmentService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("equipment");
            //子方法包装增加条件的语句，返回构建好的FunctionScoreQueryBuilder
            FunctionScoreQueryBuilder functionScoreQuery = buildeBasicQuery(requestParams);
            /*functionScoreQuery放入request中
             * 最开始query()中传入的是单个的QueryBuilders.matchQuery...
             * 之后需要多条件查询，使用了BoolQueryBuilder
             * 之后需要根据需求自定义算分，改用FunctionScoreQueryBuilder(
             *      其中包含了原始查询BoolQueryBuilder，增加了具体的一个FunctionScore，
             *      FunctionScore中有一个QueryBuilders，符合规则的才进行算分增加，
             *      指定了weightFactorFunction，作为算分函数)
             * */
            request.source().query(functionScoreQuery);

            //再进行分页的设置
            int page = requestParams.getPage();
            int size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);

            //根据用户的位置，进行设备排序
            String location = requestParams.getLocation();
            if (location != null && !"".equals(location)) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 构建多种条件查询的FunctionScoreQueryBuilder
     *
     * @param requestParams 前端传入的参数
     * @return 构建好条件并按需求增加算分的FunctionScoreQueryBuilder
     */
    private FunctionScoreQueryBuilder buildeBasicQuery(RequestParams requestParams) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //先根据关键字查询
        String key = requestParams.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }
        //城市条件
        String city = requestParams.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
        //品牌条件
        String brand = requestParams.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        //等级条件
        String starName = requestParams.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
        //价格条件
        Integer minPrice = requestParams.getMinPrice();
        Integer maxPrice = requestParams.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price")
                    .gte(minPrice)
                    .lte(maxPrice));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                //构建算分查询
                QueryBuilders.functionScoreQuery(
                        //原始查询（在原始查询的基础上进行算分控制，先查出来再改分数）
                        boolQueryBuilder,
                        //算分FunctionScore数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                //具体的一个FunctionScore
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        //过滤条件（只给符合条件的数据增加算分）
                                        QueryBuilders.termQuery("isAD", true),
                                        //用weight指定增加的算分
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });
        return functionScoreQuery;
    }

    /**
     * 解析Response
     *
     * @param response 返回的响应
     * @return 包装好的PageResult
     */
    private PageResult handleResponse(SearchResponse response) {
        List<EquipmentDoc> equipmentsDocList = new ArrayList<>();
        SearchHits responseHits = response.getHits();
        SearchHit[] hits = responseHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            EquipmentDoc equipmentsDoc = JSON.parseObject(json, EquipmentDoc.class);
            equipmentsDocList.add(equipmentsDoc);
            //获取排序值（距离km）
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                equipmentsDoc.setDistance(sortValues[0]);
            }
        }
        long total = responseHits.getTotalHits().value;

        System.out.println(equipmentsDocList);

        return new PageResult(total, equipmentsDocList);
    }

    @Override
    public Map<String, List<String>> filters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("equipment");
            //限定聚合范围（聚合前先查询）
            FunctionScoreQueryBuilder functionScoreQuery = buildeBasicQuery(requestParams);
            request.source().query(functionScoreQuery);

            //为0表示结果不含文档数据
            request.source().size(0);
            //子函数构建聚合request
            buildAggregation(request);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析聚合结果
            Aggregations aggregations = response.getAggregations();
            //存储多个聚合结果<聚合名称,聚合结果集>
            Map<String, List<String>> resultMap = new HashMap<>();
            //根据品牌名称，获取品牌结果集
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            resultMap.put("brand", brandList);
            //根据城市名称，获取城市结果集
            List<String> cityList = getAggByName(aggregations, "cityAgg");
            resultMap.put("city", cityList);
            //根据星级名称，获取星级结果集
            List<String> starList = getAggByName(aggregations, "starNameAgg");
            resultMap.put("starName", starList);

            return resultMap;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将聚合函数的结果，根据aggName封装到List<String>中
     *
     * @param aggregations 聚合函数结果集
     * @param aggName      聚合函数名称
     * @return 按聚合函数名称封装的list
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取聚合结果
        Terms terms = aggregations.get(aggName);
        //获取桶
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        //存储聚合结果
        List<String> resultList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //获取信息
            String bucketValue = bucket.getKeyAsString();
            resultList.add(bucketValue);
        }
        return resultList;
    }

    /**
     * 构建聚合request
     *
     * @param request 要构建的request
     */
    private void buildAggregation(SearchRequest request) {
        //品牌聚合
        request.source().aggregation(AggregationBuilders
                //给聚合起名字
                .terms("brandAgg")
                //要聚合的字段
                .field("brand")
                .size(100)
        );
        //城市聚合
        request.source().aggregation(AggregationBuilders
                //给聚合起名字
                .terms("cityAgg")
                //要聚合的字段
                .field("city")
                .size(100)
        );
        //星级聚合
        request.source().aggregation(AggregationBuilders
                //给聚合起名字
                .terms("starNameAgg")
                //要聚合的字段
                .field("starName")  //.keyword字段类型动态修改为keyword
                //希望获取的数量
                .size(100)
        );
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            SearchRequest request = new SearchRequest("equipment");
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "equipmentSuggestion",  //给查询命名
                    SuggestBuilders.completionSuggestion("suggestion")  //查询的字段
                            .prefix(prefix) //查询的关键字
                            .skipDuplicates(true)   //跳过重复
                            .size(10)   //获取十条数据
            ));
            //解析结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("equipmentSuggestion");

            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> valueList = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String value = option.getText().string();
                valueList.add(value);
            }
            return valueList;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void insertOrUpdateById(Long id) {
        try {
            //先根据ID从数据库中查出新增或修改的设备
            Equipment equipment = this.getById(id);
            //转化为ES文档对应的数据
            EquipmentDoc equipmentDoc = new EquipmentDoc(equipment);
            //编辑请求
            IndexRequest indexRequest = new IndexRequest("equipment").id(equipmentDoc.getId().toString());
            indexRequest.source(JSON.toJSONString(equipmentDoc), XContentType.JSON);

            //ES文档更新
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("equipment", id.toString());
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

}
